<script setup lang="ts">
import { ref, reactive, onMounted, Ref, onBeforeUnmount, shallowRef } from 'vue'
import { Message } from '@arco-design/web-vue'
import ProjectCard from '@/components/projects/ProjectCard.vue'
import { IconTag } from '@arco-design/web-vue/es/icon'
import { addProjectUsingPost, pageProjectUsingPost } from '@/api/projectController'
import { useTeamStore, useUserStore } from '@/store/index'
import { pageUserInTeamUsingPost } from '@/api/teamController'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const teamStore = useTeamStore()
const userStore = useUserStore()
// 项目列表数据
const projects = ref<API.ProjectVo[]>([])
const totalProjects = ref(0)
// 负责人选项
const ownerOptions = ref<API.User[]>([])
//查询本团队的成员
const loadOwners = async () => {
  const teamId = teamStore.selectedTeam?.id
  if (!teamId) return
  const res: any = await pageUserInTeamUsingPost({
    current: 1,
    pageSize: 1000,
    teamId
  })
  ownerOptions.value = res.data.records || []
}
// 查询参数
const pageProjectRequest: Ref<API.PageProjectRequest> = ref({
  current: 1,
  pageSize: 1000,
  teamId: teamStore?.selectedTeam?.id,
  title: '',
  code: undefined,
  ownerId: undefined
})
// 加载项目列表
const loadProjects = async () => {
  try {
    const res: any = await pageProjectUsingPost(pageProjectRequest.value)

    if (res.code === 0) {
      projects.value = res.data.records || []
      totalProjects.value = res.data.total || 0
    } else {
      Message.error(res.message || '获取项目列表失败')
    }
  } catch (error) {
    console.error('Failed to load projects:', error)
    Message.error('获取项目列表失败')
  }
}

// 搜索处理
const handleSearch = async () => {
  pageProjectRequest.value.current = 1 // 重置页码
  await loadProjects()
}

// 创建项目表单
const createForm: Ref<API.AddProjectRequest> = ref({
  teamId: teamStore.selectedTeam?.id,
  status: 0,
  title: '',
  ownerId: undefined as number | undefined,
  description: '',
  remark: '',
  memberIds: [] as number[],
  startTime: '',
  endTime: '',
  canDelay: 1
})

// 单独处理时间范围
const timeRange = ref<string[]>([])

// 监听时间范围变化
const handleTimeRangeChange = (dates: [string, string]) => {
  if (dates && dates.length === 2) {
    // 更新表单中的开始和结束时间
    createForm.value.startTime = `${dates[0]}T00:00:00`
    createForm.value.endTime = dates[1] ? `${dates[1]}T23:59:59` : '2099-12-31T23:59:59'
  }
}

// 创建项目对话框
const createDialogVisible = ref(false)

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 编辑器配置
const toolbarConfig = {}
const editorConfig = { placeholder: '请输入项目介绍...' }

// 编辑器模式
const mode = ref('default')

// 编辑器创建完成时的回调
const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例
}

// 编辑器内容变化时更新表单
const handleEditorChange = (editor: any) => {
  createForm.value.description = editor.getHtml()
}

// 备注编辑器实例
const remarkEditorRef = shallowRef()

// 备注编辑器配置
const remarkEditorConfig = { placeholder: '请输入项目备注...' }

// 备注编辑器创建完成时的回调
const handleRemarkCreated = (editor: any) => {
  remarkEditorRef.value = editor
}

// 备注编辑器内容变化时更新表单
const handleRemarkChange = (editor: any) => {
  createForm.value.remark = editor.getHtml()
}

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入项目名称' }],
  ownerId: [{ required: true, message: '请选择负责人' }],
  // 修改时间验证规则
  timeRange: [
    {
      required: true,
      message: '请选择项目时间',
      // 添加验证函数
      validator: (value: string[]) => {
        return value && value.length === 2 && value[0] && value[1]
      }
    }
  ],
  description: [{ required: true, message: '请输入项目介绍' }],
  memberIds: [{ required: true, message: '请选择项目成员' }]
}

// 重置表单时也要重置时间范围
const resetForm = () => {
  Object.assign(createForm.value, {
    title: '',
    ownerId: undefined,
    description: '',
    remark: '',
    memberIds: [],
    startTime: '',
    endTime: '',
    canDelay: 1
  })
  // 重置时间范围
  timeRange.value = []
}

// 处理对话框关闭
const handleClose = () => {
  resetForm()
  createDialogVisible.value = false
}

// 处理取消按钮点击
const handleCancel = () => {
  handleClose()
}

// 监听对话框可见性变化
const handleVisibleChange = (visible: boolean) => {
  if (!visible) {
    // 关闭对话框时销毁编辑器
    if (editorRef.value) {
      editorRef.value.destroy()
      editorRef.value = null
    }
    if (remarkEditorRef.value) {
      remarkEditorRef.value.destroy()
      remarkEditorRef.value = null
    }
  }
}

// 处理表单提交
const handleSubmit = async (done: (boolean) => void) => {
  try {
    // 打印表单数据
    console.log('创建项目参数:', {
      name: createForm.value.title,
      ownerId: createForm.value.ownerId,
      startTime: createForm.value.startTime,
      endTime: createForm.value.endTime,
      description: createForm.value.description,
      memberIds: createForm.value.memberIds
    })
    // TODO: 调用创建项目API
    const res: any = await addProjectUsingPost(createForm.value)
    if (res.code === 0) {
      Message.success('创建成功')
      handleClose()
      done(true)
      await loadProjects() // 重新加载项目列表
    } else {
      Message.error(res.message || '创建失败')
      done(false)
    }
  } catch (error) {
    console.error('创建项目失败:', error)
    done(false)
    Message.error('创建失败')
  }
}

// 创建项目
const handleCreateProject = () => {
  createDialogVisible.value = true
}

// 页面加载时获取数据
onMounted(async () => {
  await loadOwners()
  await loadProjects()
})

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap = {
    0: '进行中',
    1: '已完成',
    2: '已暂停',
    3: '未开始'
  }
  return statusMap[status as keyof typeof statusMap]
}

// 获取状态颜色
const getStatusColor = (status: number) => {
  const colorMap = {
    0: 'blue',
    1: 'green',
    2: 'orange',
    3: 'gray'
  }
  return colorMap[status as keyof typeof colorMap]
}

// 监听负责人选择变化
const handleOwnerChange = (newOwnerId: string | number | undefined) => {
  const oldOwnerId = createForm.value.ownerId
  const newOwnerIdNum = newOwnerId ? Number(newOwnerId) : undefined
  createForm.value.ownerId = newOwnerIdNum

  // 如果成员列表为空，直接添加新负责人
  if (createForm.value?.memberIds?.length === 0 && newOwnerIdNum) {
    createForm.value.memberIds = [newOwnerIdNum]
  }
  // 如果成员列表只有一个成员且是旧负责人，直接替换为新负责人
  else if (
    createForm.value?.memberIds?.length === 1 &&
    createForm.value?.memberIds?.[0] === oldOwnerId &&
    newOwnerIdNum
  ) {
    createForm.value.memberIds = [newOwnerIdNum]
  }
  // 如果成员列表有多个成员，且包含旧负责人，则替换旧负责人为新负责人
  else if (newOwnerIdNum && oldOwnerId && createForm.value?.memberIds?.includes(oldOwnerId)) {
    createForm.value.memberIds = createForm.value.memberIds.map((id) =>
      id === oldOwnerId ? newOwnerIdNum : id
    )
  }
  // 如果成员列表不包含新负责人，则添加到列表中
  else if (newOwnerIdNum && !createForm.value?.memberIds?.includes(newOwnerIdNum)) {
    createForm.value.memberIds = [newOwnerIdNum, ...(createForm.value?.memberIds || [])]
  }
  console.log(createForm.value.memberIds)
}

// 监听成员变化
const handleMembersChange = (values: (string | number)[]) => {
  // 如果移除了负责人，清空负责人选择
  if (createForm.value?.ownerId && !values?.includes(createForm.value.ownerId)) {
    createForm.value.ownerId = undefined
  }
}

// 获取用户名称
const getUserName = (id: number) => {
  const user = ownerOptions.value.find((user) => user.id === id)
  return user ? user.name : id.toString()
}
</script>

<template>
  <div class="projects-container">
    <!-- 标题行 -->
    <div class="header-row">
      <h2 class="title">全部项目</h2>
      <a-button type="primary" @click="handleCreateProject">
        <template #icon>
          <icon-plus />
        </template>
        新建项目
      </a-button>
    </div>

    <!-- 搜索行 -->
    <div class="search-row">
      <div class="search-group">
        <a-input-search
          v-model="pageProjectRequest.title"
          placeholder="搜索项目(enter搜索)"
          search-button
          @press-enter="handleSearch"
          @search="handleSearch"
        />
        <a-input
          v-model="pageProjectRequest.code"
          placeholder="项目代码"
          allow-clear
          @press-enter="handleSearch"
        >
          <template #prefix>
            <icon-tag />
          </template>
        </a-input>
        <a-select
          v-model="pageProjectRequest.ownerId"
          placeholder="负责人"
          allow-clear
          @change="handleSearch"
        >
          <a-option v-for="owner in ownerOptions" :key="owner.id" :value="owner.id">{{
            owner.name
          }}</a-option>
        </a-select>
      </div>
      <div class="project-count">共 {{ totalProjects }} 个项目</div>
    </div>

    <!-- 项目网格 -->
    <a-grid :colGap="12" :rowGap="16" :cols="{ xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }" class="projects-grid">
      <a-grid-item class="projects-grid-item" v-for="project in projects" :key="project.id">
        <ProjectCard :key="project.id" :project="project" />
      </a-grid-item>
    </a-grid>
    <!-- 创建项目对话框 -->
    <a-modal
      v-model:visible="createDialogVisible"
      title="创建项目"
      :modal-style="{ width: '800px', top: '20px' }"
      :mask-closable="false"
      :closable="false"
      @before-ok="handleSubmit"
      @cancel="handleCancel"
      @update:visible="handleVisibleChange"
    >
      <a-form :model="createForm" :rules="rules" layout="vertical">
        <!-- 项目名称 -->
        <a-form-item field="title" label="项目名称" validate-trigger="blur">
          <a-input v-model="createForm.title" placeholder="请输入项目名称" allow-clear />
        </a-form-item>

        <!-- 负责人和推延选项放在同一行 -->
        <div class="form-row">
          <a-form-item field="ownerId" label="负责人" :style="{ flex: 2 }">
            <a-select
              v-model="createForm.ownerId"
              placeholder="请选择负责人"
              allow-clear
              @change="handleOwnerChange"
            >
              <a-option v-for="owner in ownerOptions" :key="owner.id" :value="owner.id">
                {{ owner.name }}
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="canDelay" label="允许推延" :style="{ flex: 1 }">
            <a-select v-model="createForm.canDelay" placeholder="请选择是否允许推延">
              <a-option :value="1">允许</a-option>
              <a-option :value="0">不允许</a-option>
            </a-select>
          </a-form-item>
        </div>

        <!-- 项目时间 -->
        <a-form-item field="timeRange" label="项目时间">
          <a-range-picker v-model="timeRange" style="width: 100%" @change="handleTimeRangeChange" />
        </a-form-item>

        <!-- 项目介绍 -->
        <a-form-item field="description" label="项目介绍">
          <div class="editor-container" v-if="createDialogVisible">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :default-config="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px"
              v-model="createForm.description"
              :default-config="editorConfig"
              :mode="mode"
              @on-created="handleCreated"
              @on-change="handleEditorChange"
            />
          </div>
        </a-form-item>

        <!-- 项目成员 -->
        <a-form-item field="memberIds" label="项目成员">
          <a-select
            v-model="createForm.memberIds"
            placeholder="请选择项目成员"
            multiple
            allow-create
            allow-search
            @change="handleMembersChange"
          >
            <a-option v-for="owner in ownerOptions" :key="owner.id" :value="owner.id">
              {{ owner.name }}
            </a-option>
          </a-select>
        </a-form-item>

        <!-- 项目备注 -->
        <a-form-item field="remark" label="项目备注">
          <div class="editor-container" v-if="createDialogVisible">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="remarkEditorRef"
              :default-config="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px"
              v-model="createForm.remark"
              :default-config="remarkEditorConfig"
              :mode="mode"
              @on-created="handleRemarkCreated"
              @on-change="handleRemarkChange"
            />
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped>
.projects-container {
  padding: 16px;
}

.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  gap: 16px;
}

.search-group {
  display: flex;
  gap: 16px;
  /* flex: 1; */
}

/* 所有搜索框固定宽度 */
.search-group :deep(.arco-input-wrapper),
.search-group :deep(.arco-select) {
  flex: 0 0 200px !important;
  width: 200px !important;
}

.project-count {
  color: var(--color-text-3);
  font-size: 14px;
  white-space: nowrap;
}

.projects-grid {
  padding: 8px 0;
  overflow: auto;
  height: calc(100vh - 276px);
}

.editor-container {
  border: 1px solid var(--color-border);
  border-radius: 4px;
}

:deep(.w-e-text-container) {
  height: 300px !important;
}

/* 调整编辑器内容区域的样式 */
:deep(.w-e-text-container [data-slate-editor]) {
  padding: 0 10px;
}

:deep(.w-e-text-container [data-slate-editor] p) {
  margin: 8px 0; /* 减小段落间距 */
  line-height: 1.5; /* 减小行高 */
}

/* 调整工具栏样式 */
:deep(.w-e-toolbar) {
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  border-bottom: 1px solid var(--color-border);
  padding: 0 10px;
}

:deep(.arco-modal-content) {
  max-height: calc(100vh - 120px);
  overflow-y: auto;
}

/* 编辑器全屏时的样式调整 */
:deep(.w-e-full-screen-container) {
  z-index: 2000 !important; /* 确保高于模态框的 z-index */
}

/* 调整模态框的 z-index */
:deep(.arco-modal-container) {
  z-index: 1000;
}

/* 调整模态框遮罩的 z-index */
:deep(.arco-modal-mask) {
  z-index: 999;
}

/* 调整表单项样式 */
:deep(.arco-form-item) {
  margin-bottom: 24px;
}

:deep(.arco-form-item-label) {
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--color-text-1);
}

:deep(.arco-form-item-wrapper) {
  width: 100%;
}

:deep(.arco-input-wrapper),
:deep(.arco-select),
:deep(.arco-picker) {
  width: 100%;
}

:deep(.arco-select-view-tag) {
  max-width: 100px; /* 限制标签最大宽度 */
}

/* 添加新的样式 */
.form-row {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

:deep(.arco-form-item) {
  margin-bottom: 24px;
  width: 100%;
}

:deep(.arco-switch) {
  margin-top: 4px; /* 微调开关的垂直对齐 */
}

.projects-grid-item {

}
</style>
